package com.chushouya.product.service.api.impl;

import com.general.framework.core.lang.Beans;
import com.general.framework.core.schema.PageResult;
import com.chushouya.product.dao.entity.BrandEntity;
import com.chushouya.product.dao.entity.CategoryBrandEntity;
import com.chushouya.product.dao.repository.BrandRepository;
import com.chushouya.product.dao.repository.CategoryBrandRepository;
import com.chushouya.product.dto.admin.brand.BrandQuery;
import com.chushouya.product.dto.admin.category.CategoryBrandQuery;
import com.chushouya.product.dto.api.brand.BrandApiQuery;
import com.chushouya.product.dto.api.brand.BrandGroupApiDTO;
import com.chushouya.product.dto.api.brand.BrandGroupListApiDTO;
import com.chushouya.product.dto.api.brand.BrandListApiDTO;
import com.chushouya.product.service.api.BrandApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author CodeGenerator
 * @data 2022/05/29.
 */
@Slf4j
@Service
public class BrandApiServiceImpl implements BrandApiService {

    @Resource
    private BrandRepository brandRepository;

    @Resource
    private CategoryBrandRepository categoryBrandRepository;

    @Override
    public List<BrandListApiDTO> brandList(BrandApiQuery query) {
        BrandQuery brandQuery = Beans.copy(query, BrandQuery.class);
        CategoryBrandQuery categoryBrandQuery = Beans.copy(query, CategoryBrandQuery.class);
        PageResult<CategoryBrandEntity> categoryBrandPageResult = categoryBrandRepository.selectPage(categoryBrandQuery);
        List<CategoryBrandEntity> categoryBrandList = categoryBrandPageResult.getRows();
        if (!categoryBrandList.isEmpty()) {
            List<Long> brandIds = categoryBrandList.stream()
                    .map(CategoryBrandEntity::getBrandId)
                    .distinct()
                    .collect(Collectors.toList());
            brandQuery.setBrandIdList(brandIds);
        }

        // 查询品牌数据
        List<BrandEntity> brandResult = brandRepository.selectList(brandQuery);
        return Beans.copyList(brandResult, BrandListApiDTO.class);
    }

    @Override
    public BrandListApiDTO getBrand(Long brandId) {
        BrandQuery query = new BrandQuery();
        query.setBrandId(brandId);
        BrandEntity brandEntity = brandRepository.selectOne(query);
        return Beans.copy(brandEntity, BrandListApiDTO.class);
    }

    @Override
    public List<BrandGroupListApiDTO> getBrandGroup(BrandApiQuery query) {
        // 查询品牌数据（包含分类过滤）
        List<BrandEntity> brandList = getBrandListWithCategoryFilter(query);
        
        // 按首字母分组并转换为返回格式
        return brandList.stream()
                .collect(Collectors.groupingBy(this::getBrandInitial))
                .entrySet().stream()
                .map(this::createBrandGroup)
                .sorted(Comparator.comparing(BrandGroupListApiDTO::getInitial))
                .collect(Collectors.toList());
    }
    
    /**
     * 查询品牌列表（包含分类过滤）
     */
    private List<BrandEntity> getBrandListWithCategoryFilter(BrandApiQuery query) {
        BrandQuery brandQuery = Beans.copy(query, BrandQuery.class);
        
        // 如果有分类限制，先查询分类品牌关联数据
        if (query.getCategoryId() != null) {
            CategoryBrandQuery categoryBrandQuery = Beans.copy(query, CategoryBrandQuery.class);
            List<CategoryBrandEntity> categoryBrandList = categoryBrandRepository.selectList(categoryBrandQuery);
            
            if (!categoryBrandList.isEmpty()) {
                List<Long> brandIds = categoryBrandList.stream()
                        .map(CategoryBrandEntity::getBrandId)
                        .distinct()
                        .collect(Collectors.toList());
                brandQuery.setBrandIdList(brandIds);
            }
        }
        
        return brandRepository.selectList(brandQuery);
    }
    
    /**
     * 获取品牌首字母
     */
    private String getBrandInitial(BrandEntity brand) {
        String initial = brand.getInitial();
        return initial != null ? initial.toUpperCase() : "#";
    }
    
    /**
     * 创建品牌分组
     */
    private BrandGroupListApiDTO createBrandGroup(Map.Entry<String, List<BrandEntity>> entry) {
        BrandGroupListApiDTO groupDTO = new BrandGroupListApiDTO();
        groupDTO.setInitial(entry.getKey());
        
        List<BrandGroupApiDTO> brandList = entry.getValue().stream()
                .map(this::convertToBrandGroupApiDTO)
                .sorted(Comparator.comparing(BrandGroupApiDTO::getSort, Comparator.nullsLast(Comparator.naturalOrder()))
                        .thenComparing(BrandGroupApiDTO::getBrandName))
                .collect(Collectors.toList());
        
        groupDTO.setList(brandList);
        return groupDTO;
    }
    
    /**
     * 转换为 BrandGroupApiDTO
     */
    private BrandGroupApiDTO convertToBrandGroupApiDTO(BrandEntity brand) {
        BrandGroupApiDTO brandDTO = new BrandGroupApiDTO();
        brandDTO.setBrandId(brand.getBrandId());
        brandDTO.setBrandName(brand.getBrandName());
        brandDTO.setBrandImage(brand.getBrandImage());
        brandDTO.setInitial(brand.getInitial());
        brandDTO.setSort(brand.getSort());
        return brandDTO;
    }
}
